package cubelabs.nexus.dao;

import cubelabs.nexus.domain.SearchRequest;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import cubelabs.nexus.entity.Category;
import cubelabs.nexus.entity.User;

@Repository("categoryDAO")
public class CategoryDAO extends BaseDAO<Category, Long>{
	
	public Category findByName(String name){
		Criteria crit = getSession().createCriteria(getPersistentClass());
		crit.add((Restrictions.eq("name", name)));
		Category category  = (Category) crit.uniqueResult();
		return category;
	}
	
	@SuppressWarnings("unchecked")
	public List<User> getUsers(Long categoryId) {
		Criteria crit = getSession().createCriteria(User.class);
		crit.createAlias("categories", "categoriesAlias");
		crit.add(Restrictions.eq("categoriesAlias.id", categoryId));
		crit.add(Restrictions.eq("isExpert", true));
		List<User> users = (List<User>) crit.list();
		return users;
    }
        
        
	@SuppressWarnings("unchecked")
	public List<Category> getCategories(String category) {
		Criteria crit = getSession().createCriteria(getPersistentClass());
		crit.add((Restrictions.like("name", "%"+category+"%")));
		List<Category> categoryList  = (List<Category>) crit.list();
                return categoryList;
    }
     
	@SuppressWarnings("unchecked")
	public List<Category> findTrendingCategories(){
            SQLQuery query =  (SQLQuery) getSession().createSQLQuery("SELECT c.* FROM Category c, (SELECT category_id FROM users_category GROUP BY category_id ORDER BY COUNT(*) DESC LIMIT 15) e WHERE c.id = e.category_id");
            query.addEntity(getPersistentClass());
            List<Category> result = query.list();
            return result;

	}
}
